<?php

namespace SidToken\Model;


use Common\Model\UserModel;
use Think\Model;

class InviteUserModel extends Model
{
    public $nextLevelUpTips = "";

    public function addData($uid, $invite_uid)
    {
        $data = array(
            'uid' => $uid,
            'invite_uid' => $invite_uid,
            'create_time' => time()
        );
        return $this->add($data);
    }

    public function getInviteUids($uid)
    {
        $users = $this->where("invite_uid={$uid}")->field("uid")->select();
        return $users;
    }

    public function countInvite($uid)
    {
        return $this->where("invite_uid={$uid}")->count();
    }


    /**
     * 团队数据统计
     * @param $uid
     * @return array|mixed
     */
    public function myTeams($root_uid)
    {
        $key = "MY_TEAM_{$root_uid}";
        S($key, null);
        $data = S($key);
        if (!$data) {
            $rootUid = $root_uid;
            $amount = 0;
            $teams = array();
            $rootTeams = array();
            $this->calTeamAmount(3, $root_uid, $amount, $teams, $depth, $rootUid, $rootTeams, $rootTeamUserAmount);

            $data = array(
                'amount' => $amount,
                'teams' => $teams,
                'root_team' => $rootTeams,
                'root_team_user_amount' => $rootTeamUserAmount
            );
            S($key, $data, 600);
        }
        return $data;
    }

    /**
     * 团队树状图
     * 【格式如下】
     *  uid 用户姓名
     *   -- uid 用户姓名
     *   -- uid 用户姓名
     *      -- uid 用户姓名
     */
    public function inviteTree($rootUid, $uid = 0, &$tree = [], &$totalAmount = 0, &$totalScore1 = 0, &$totalScore2 = 0, &$totalScore3 = 0, &$totalScore4 = 0, &$totalScore5 = 0)
    {
        if (!$uid) {
            $uid = $rootUid;
            $memberScore = D("Member")->where("uid={$uid}")->field("score1+score1_d score1,score2+score2_d score2,score3+score3_d score3,score4+score4_d score4,score5+score5_d score5")->find();
            $totalAmount++;
            foreach ($memberScore as $key => &$val) {
                $val = floatval($val);
                if ($key == 'score1') {
                    $totalScore1 += $val;
                }
                if ($key == 'score2') {
                    $totalScore2 += $val;
                }
                if ($key == 'score3') {
                    $totalScore3 += $val;
                }
                if ($key == 'score4') {
                    $totalScore4 += $val;
                }
                if ($key == 'score5') {
                    $totalScore5 += $val;
                }
            }

            $tree["1_{$rootUid}"]['text'] = "用户：[{$rootUid}] " . get_name($rootUid) . "[A积分：{$memberScore['score1']}][B积分：{$memberScore['score5']}][C积分：{$memberScore['score4']}][USDT：{$memberScore['score2']}][锁仓A积分：{$memberScore['score3']}]";
            $tree["1_{$rootUid}"]['id'] = $rootUid;
        }
        $uids = $this->where("invite_uid={$uid}")->field("uid")->select();

        foreach ($uids as $v) {
            $child = $v['uid'];
            $memberScore = D("Member")->where("uid={$child}")->field("score1+score1_d score1,score2+score2_d score2,score3+score3_d score3,score4+score4_d score4,score5+score5_d score5")->find();
            $totalAmount++;
            foreach ($memberScore as $key => &$val) {
                $val = floatval($val);
                if ($key == 'score1') {
                    $totalScore1 += $val;
                }
                if ($key == 'score2') {
                    $totalScore2 += $val;
                }
                if ($key == 'score3') {
                    $totalScore3 += $val;
                }
                if ($key == 'score4') {
                    $totalScore4 += $val;
                }
                if ($key == 'score5') {
                    $totalScore5 += $val;
                }
            }
            $tree["{$uid}_{$child}"]['text'] = "用户：[{$child}] " . get_name($child) . "[A积分：{$memberScore['score1']}][B积分：{$memberScore['score5']}][C积分：{$memberScore['score4']}][USDT：{$memberScore['score2']}][锁仓A积分：{$memberScore['score3']}]";;
            $tree["{$uid}_{$child}"]['id'] = $child;
            $this->inviteTree($rootUid, $child, $tree, $totalAmount, $totalScore1, $totalScore2, $totalScore3, $totalScore4, $totalScore5);
        }
    }

    /**
     * 统计三代
     * @param $uid
     */
    public function levelAnalysis($uid, &$depth = 0, &$level1Amount = 0, &$level2Amount = 0, &$level3Amount = 0, &$level1Uids = [], &$level2Uids = [], &$level3Uids = [])
    {
        if ($depth == 0) {//一代
            $uids = M("InviteUser")->where("invite_uid={$uid}")->field("uid")->select();
            $level1Amount = sizeof($uids);
            $level1Uids = getSubByKey($uids, 'uid');
            $depth++;
            $this->levelAnalysis($uid, $depth, $level1Amount, $level2Amount, $level3Amount, $level1Uids, $level2Uids, $level3Uids);

        } else if ($depth == 1) {//二代
            foreach ($level1Uids as $uid) {
                $uids = M("InviteUser")->where("invite_uid={$uid}")->field("uid")->select();
                foreach ($uids as $val) {
                    $level2Uid = $val['uid'];
                    $level2Uids[] = $level2Uid;
                    $level2Amount++;
                }
            }
            $depth++;
            $this->levelAnalysis($uid, $depth, $level1Amount, $level2Amount, $level3Amount, $level1Uids, $level2Uids, $level3Uids);

        } else if ($depth == 2) {//三代
            foreach ($level2Uids as $uid) {
                $uids = M("InviteUser")->where("invite_uid={$uid}")->field("uid")->select();
                foreach ($uids as $val) {
                    $level3Uid = $val['uid'];
                    $level3Uids[] = $level3Uid;
                    $level3Amount++;
                }
            }
            $depth++;
            $this->levelAnalysis($uid, $depth, $level1Amount, $level2Amount, $level3Amount, $level1Uids, $level2Uids, $level3Uids);
        }
    }

    private function calTeamAmount($maxDepth, $uid, &$amount = 0, &$teams = array(), &$depth = 1, &$rootUid, &$rootTeams, &$rootTeamUserAmount, $inviteUid = 0)
    {
        //$SK_WALLET_CONFIG = C("SK_WALLET_CONFIG");
        //$grant_trade_invite_profit_level = $SK_WALLET_CONFIG['grant_trade_invite_profit_level'];
        //
        $uids = M("InviteUser")->where("invite_uid={$uid}")->field("uid")->select();
        $inviteUid = $uid;
        if ($uids == null) {
            return;
        }
        $isRoot = $uid == $rootUid ? true : false;
        foreach ($uids as $val) {
            $uid_ = $val['uid'];
            $amount++;
            $teams[] = $uid_;
            if ($isRoot) {
                $rootTeams[] = $uid_;
            }
            $isInRootTeam = in_array($inviteUid, $rootTeams) ? true : false;//是一级团队成员，统计该成员下团队人数
            if ($isInRootTeam) {
                $rootTeamUserAmount[$inviteUid]++;
            }
            $depth++;
            if ($depth > $maxDepth) {
                return;
            } else {
                $this->calTeamAmount($maxDepth, $uid_, $amount, $teams, $depth, $rootUid, $rootTeams, $rootTeamUserAmount, $inviteUid);
            }

        }
    }

    public function getInviteUid($uid, $level)
    {
        $data = redis("invite_{$uid}_{$level}");
        if (!$data) {
            if (!$uid) {
                return 0;
            }
            $index = 0;
            $indexUid = $uid;
            $inviteUid = 0;
            while ($index < $level) {
                $inviteUid = $this->where(['uid' => $indexUid])->getField("invite_uid");
                if (!$inviteUid) {
                    break;
                }else{
                    $indexUid = $inviteUid;
                    $index++;
                }

            }
            $data = intval($inviteUid);
            redis("invite_{$uid}_{$level}", $data);
        }
        return intval($data);
    }
}